<template>
    <div id="accessManage">
        <div style="display: flex;">
            <div style="width: 300px;height: 300px ;">
                <el-tree :data="formattedTreeData" accordion v-model="selectLocation" @node-click="handleNodeClick"></el-tree>
            </div>
            <div style="margin-left: 20px;">
                设备编号 <el-input v-model="selectCode" placeholder="请输入设备编号" style="width: 150px;"></el-input>
                设备名称 <el-input v-model="selectName" placeholder="请输入设备名称" style="width: 150px;"></el-input>
                创建时间 <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
                <el-button type="primary" style="height: 35px;" @click="getSysDeviceList()"><i
                        class="el-icon-search">搜索</i></el-button>
                <el-button style="height: 35px;" @click="reset"><i class="el-icon-refresh">重置</i></el-button>
                <div style="margin-top: 10px;">
                    <el-button type="primary" style="height: 35px;" @click.native="addEquipmentValue"><i
                            class="el-icon-plus">新增</i></el-button>
                </div>
            </div>
        </div>
        <el-row v-if="addEquipment">
            <el-dialog title="添加人脸闸机设备" :visible.sync="addEquipment" width="43%">
                <el-form label-width="100px" :rules="rules" class="demo-ruleForm" style="height: 430px;">
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;" prop="name">
                            <span style="color: red;">*</span>
                            序列编号 <el-input placeholder="请输入序列编号" v-model="code" style="width: 200px;"></el-input>
                        </div>
                        <div style="flex: 1;margin-right: 5px;">
                            <span style="color: red;">*</span>
                            设备编号 <el-input placeholder="请输入设备名称" v-model="name" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            常开时段 <el-input placeholder="请输入常开时段编号" v-model="openTime" style="width: 200px;"></el-input>
                        </div>

                        <div style="flex: 1;">
                            出入类型
                            <el-select v-model="statusValue" placeholder="请选择设备类型" @change="selectChange">
                                <el-option label="入口" value="入口"></el-option>
                                <el-option label="出口" value="出口"></el-option>
                            </el-select>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            常闭时段 <el-input placeholder="请输入常闭时段编号" v-model="closeTime" style="width: 200px;"></el-input>
                        </div>
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            用户名 <el-input placeholder="请输入设备SDK用户名" v-model="username" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            密码
                            <el-input placeholder="请输入设备SDK密码" v-model="password" style="width: 200px;"></el-input>
                        </div>
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            IP地址 <el-input placeholder="请输入内容" v-model="ipAddress" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            端口号
                            <el-input placeholder="请输入设备端口号" v-model="port" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            空间位置<el-cascader v-model="location" :options="formattedTreeData"
                                :props="{ checkStrictly: true }" clearable>
                            </el-cascader>
                        </div>
                    </div>
                    <div style="display: flex;gap: 10px;position: absolute;right: 20px;bottom: 0;height: 50px;">
                        <span slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="add">确定</el-button>
                            <el-button @click="addEquipment = false">取 消</el-button>
                        </span>
                    </div>
                </el-form>
            </el-dialog>
        </el-row>
        <div v-for="device in sysDeviceList" :key="device.deviceSerialNumber" class="device-item">
            <el-card class="device-info">
                <span style="color: aqua;" @click="upd(device)">{{ device.name }}</span>
                <hr>
                <p>设备位置: {{ device.location }}</p>
                <p>设备 IP: {{ device.ipAddress }}</p>
                <p>设备序列号: {{ device.code }}</p>
                <p>状态:
                    <span @click="subscribe(device)" >订阅  </span>
                    <span>{{ device.status == 0 ? ' 离线 ' : ' 在线 ' }}</span>
                    <span @click="refresh(device.id)"><i class="el-icon-refresh"></i></span>
                    <i class="el-icon-delete"
                        @click="del(device.id)"></i>
                        
                </p>
                
            </el-card>
        </div>
        <el-row v-if="updEquipment">
            <el-dialog title="修改人脸闸机设备" :visible.sync="updEquipment" width="43%">
                <el-form label-width="100px" class="demo-ruleForm" style="height: 430px;">
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            序列编号 <el-input placeholder="请输入序列编号" v-model="code" style="width: 200px;"></el-input>
                        </div>
                        <div style="flex: 1;margin-right: 5px;">
                            <span style="color: red;">*</span>
                            设备编号 <el-input placeholder="请输入设备名称" v-model="name" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            常开时段 <el-input placeholder="请输入常开时段编号" v-model="openTime" style="width: 200px;"></el-input>
                        </div>

                        <div style="flex: 1;">
                            出入类型
                            <el-select v-model="statusValue" placeholder="请选择设备类型" @change="selectChange">
                                <el-option label="入口" value="入口"></el-option>
                                <el-option label="出口" value="出口"></el-option>
                            </el-select>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            常闭时段 <el-input placeholder="请输入常闭时段编号" v-model="closeTime" style="width: 200px;"></el-input>
                        </div>
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            用户名 <el-input placeholder="请输入设备SDK用户名" v-model="username" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            密码
                            <el-input placeholder="请输入设备SDK密码" v-model="password" style="width: 200px;"></el-input>
                        </div>
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            IP地址 <el-input placeholder="请输入内容" v-model="ipAddress" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            端口号
                            <el-input placeholder="请输入设备端口号" v-model="port" style="width: 200px;"></el-input>
                        </div>
                    </div>
                    <div style="display: flex; gap: 60px;margin-left: 22px;height: 65px;">
                        <div style="flex: 1;">
                            <span style="color: red;">*</span>
                            空间位置<el-cascader v-model="location" :options="formattedTreeData"
                                :props="{ checkStrictly: true }" clearable>
                            </el-cascader>
                        </div>
                    </div>
                    <div style="display: flex;gap: 10px;position: absolute;right: 20px;bottom: 0;height: 50px;">
                        <span slot="footer" class="dialog-footer">
                            <el-button type="primary" @click="updDevice">确定</el-button>
                            <el-button @click="updEquipment = false">取 消</el-button>
                        </span>
                    </div>
                </el-form>
            </el-dialog>
        </el-row>
    </div>
</template>
<script>
import axios from 'axios';
export default {
    name: 'accessManage',
    data() {
        return {
            aaa: '',
            addEquipment: false,
            from: {},
            value1: '',
            sysDormitoryList: [],
            checkStrictly: false,
            code: '',
            name: '',
            type: '',
            port: '',
            openTime: '',
            closeTime: '',
            username: '',
            password: '',
            ipAddress: '',
            location: '',
            statusValue: '',
            sysDeviceList: [],
            selectCode: '',
            selectName: '',
            selectLocation: '',
            updEquipment: false,
            sysClassroomList: [],
            selectLocationJoin: [],
            rules: {
                name: [
                    { required: true, message: '请输入活动名称', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getSysDormitoryList();
        this.getSysDeviceList();
        this.getSysClassroomList();
    },
    computed: {
        formattedTreeData() {
            const formattedData = [];
            function processData(data) {
                data.forEach(item => {
                    const sysDormitoryList = {
                        label: item.locationName,
                        value: item.locationName,
                        children: item.floorNumber
                            ? Array.from({ length: item.floorNumber }, (_, index) => ({
                                label: `${index + 1}楼`,
                                value: `${index + 1}楼`,
                                children: [

                                ]
                            }))
                            : []
                    };
                    formattedData.push(sysDormitoryList);
                });
                return formattedData;
            }
            return processData(this.sysDormitoryList);
        },
    },
    methods: {
        addEquipmentValue() {
            this.code = '';
            this.name = '';
            this.statusValue = '';
            this.port = '';
            this.openTime = '';
            this.closeTime = '';
            this.username = '';
            this.password = '';
            this.ipAddress = '';
            this.location = '';
            this.addEquipment = true;
        },
        getSysDormitoryList() {

            this.Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/dormitory/getSysDormitoryList',
                method: 'post',
                headers: {
                    'Authorization': this.Authorization
                }
            })
                .then(response => {
                    console.log(response);
                    this.sysDormitoryList = response.data.data;
                })
        },
        add() {
            console.log("aaaaa");
            console.log("code" + this.code);
            console.log("name" + this.name);
            console.log("type" + this.statusValue);
            console.log("port" + this.port);
            console.log("openTime" + this.openTime);
            console.log("closeTime" + this.closeTime);
            console.log("username" + this.username);
            console.log("password" + this.password);
            console.log("ipAddress" + this.ipAddress);
            console.log("location" + this.location.join('/'));
            if (this.code == "") {
                alert("请输入设备编号");
                return;
            }
            this.Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/device/add',
                method: 'post',
                data: {
                    code: this.code,
                    name: this.name,
                    type: this.statusValue,
                    port: this.port,
                    openTime: this.openTime,
                    closeTime: this.closeTime,
                    username: this.username,
                    password: this.password,
                    ipAddress: this.ipAddress,
                    location: this.location.join('/'),
                },
                headers: {
                    'Authorization': this.Authorization
                }
            })
                .then(response => {
                    console.log(response);
                    if (response.data.status == 200) {
                        this.$message.success('设备信息添加成功！');
                        this.addEquipment = false;
                    } else {
                        this.$message.error('设备信息添加失败！');
                    }
                })
        },
        selectChange(statusValue) {
            console.log(this.selectValue);
            this.type = statusValue;
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        },
        getSysDeviceList() {
            this.Authorization = localStorage.getItem("Authorization");

            if (this.value1 && this.value1.length === 2) {
                const startDate = this.value1[0];
                const endDate = this.value1[1];
                console.log('开始日期：', startDate);
                const formattedStartDate = this.formatDate(startDate);
                const formattedEndDate = this.formatDate(endDate);

                console.log('开始日期：', formattedStartDate);
                console.log('结束日期：', formattedEndDate);
                this.startDate = formattedStartDate,
                this.endDate = formattedEndDate;
            }
            let aa;
            if(this.selectLocationJoin != ''){
                aa = this.selectLocationJoin.join('/');
            }else{
                aa = '';
            }
            console.log(aa);
            axios({
                url: 'http://localhost:9002/sys/device/getSysDeviceList',
                method: 'post',
                params: {
                    code: this.selectCode,
                    name: this.selectName,
                    location: aa,
                    startDate: this.startDate,
                    endDate: this.endDate
                },
                headers: {
                    'Authorization': this.Authorization
                }
            })
                .then(response => {
                    console.log(response);
                    this.sysDeviceList = response.data.data.sysDeviceList;
                    this.selectLocationJoin = [];
                })
        },
        upd(device) {
            this.device = device;
            console.log(device);
            this.code = this.device.code;
            this.name = this.device.name;
            this.statusValue = this.device.type;
            this.port = this.device.port;
            this.openTime = this.device.openTime;
            this.closeTime = this.device.closeTime;
            this.username = this.device.username;
            this.password = this.device.password;
            this.ipAddress = this.device.ipAddress;
            this.location = this.device.location.split('/');
            // this.location = locationStr; 
            console.log("aaaaaa");
            console.log(this.location);
            this.updEquipment = true;
        },
        updDevice() {
            let Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/device/upd',
                method: 'post',
                data: {
                    id: this.device.id,
                    code: this.code,
                    name: this.name,
                    type: this.statusValue,
                    port: this.port,
                    openTime: this.openTime,
                    closeTime: this.closeTime,
                    username: this.username,
                    password: this.password,
                    ipAddress: this.ipAddress,
                    location: this.location.join('/'),
                },
                headers: {
                    'Authorization': Authorization
                }
            })
                .then(response => {
                    console.log(response);
                    if (response.data.status == 200) {
                        this.$message.success('设备信息修改成功！');
                        this.updEquipment = false;
                        this.getSysDeviceList();
                    } else {
                        this.$message.error('设备信息修改失败！');
                    }
                })
        },
        getSysClassroomList() {
            this.Authorization = localStorage.getItem("Authorization");
            axios({
                url: 'http://localhost:9002/sys/classroom/getSysClassroomAll',
                method: 'post',
                headers: {
                    'Authorization': this.Authorization
                }
            })
                .then(response => {
                    console.log(response);
                    this.sysClassroomList = response.data.data.sysClassroomList;
                })
        },
        handleNodeClick(data, node) {
            console.log(data.label);
            // 获取父节点（如果存在）  
            let parentNode = node.parent;
            let parentValue = null;
            // let parentValue2 = null ;
            if (parentNode) {
                // 父节点的数据对象  
                const parentData = parentNode.data;
                // 父节点的 value  
                parentValue = parentData.value;
                console.log(parentValue)
                if (parentValue != null && parentValue != '') {
                    this.selectLocationJoin.push(parentValue);
                }
            }

            console.log(this.selectLocationJoin);

            this.selectLocationJoin.push(data.label);
            this.selectLocationJoin.join('/');
            console.log("aaaaaaaa" + this.selectLocationJoin.join('/'));
            this.getSysDeviceList();
        },
        del(id) {
            console.log(id);
            if (confirm("确定删除该设备信息？")) {
                let Authorization = localStorage.getItem("Authorization");
                axios({
                    url: 'http://localhost:9002/sys/device/delSysDeviceById',
                    method: 'post',
                    params: {
                        id: id
                    },
                    headers: {
                        'Authorization': Authorization
                    }
                })
                    .then(response => {
                        console.log(response);
                        if (response.data.status == 200) {
                            this.$message.success('设备信息删除成功！');
                            this.getSysDeviceList();
                        } else {
                            this.$message.error('设备信息删除失败！');
                        }
                    })
            }

        },
        reset(){
            this.selectCode = '';
            this.selectName = '';
            this.value1 = '';
            this.selectLocationJoin = '';
            this.startDate = '';
            this.endDate = '';
            this.getSysDeviceList(1);
        },
        refresh(id){
            axios({
                url: 'http://localhost:9002/sys/device/refresh',
                method: 'post',
                params: {
                    id: id
                },
                headers: {
                    'Authorization': this.Authorization
                }
            })
            .then(response => {
                console.log(response);
                if (response.data.status == 200) {
                    this.$message.success('设备信息刷新成功！');
                    this.getSysDeviceList();
                }else{
                    this.$message.error('设备信息刷新失败！');
                }
            })
        },
        subscribe(device){
            axios({
                url: 'http://localhost:9002/sys/device/subscribe',
                method: 'post',
                data: {
                    ...device
                },
                headers: {
                    'Authorization': this.Authorization
                }
            })
            .then(response => {
                console.log(response);
                if (response.data.status == 200) {
                    alert("订阅成功");
                }else{
                    alert("订阅失败");
                }
            })
        }
    },
}
</script>
<style scoped>
.device-item {
    display: inline-block;
    margin-right: 20px;
    width: 300px;
}

.device-info {
    text-align: left;
    height: 250px;
}
</style>
